package com.up.jiasai.handler;
/**
 * 文件对象
 * 功能说明：<br>
 * 模块名称：<br>
 * 功能描述：<br>
 * 文件名称: <br>
 * 系统名称：<br>
 * 软件著作权：icelove 版权所有<br>
 * 开发人员：icelove <br>
 * 开发时间：2019/2/22 16:38<br>
 * 系统版本：1.0.0<br>
 */

import com.up.vms.application.base.exception.SysException;
import com.up.vms.application.base.exception.TokenException;
import com.up.vms.application.base.utils.StringUtils;
import com.up.vms.application.common.utils.json.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public JsonResult defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        JsonResult result = new JsonResult(false);
        result.setStatus("500");
        result.setMsg("GlobalExceptionHandler >>> error");
        if (ex instanceof TokenException) {
            result.setMsg(ex.getMessage());
        } else if (ex instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            result.setStatus("404");
            result.setMsg("GlobalExceptionHandler >>> 找不到该接口");
        } else if (ex instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
            result.setStatus("403");
            result.setMsg("GlobalExceptionHandler >>> 请登录");
        }  else if (ex instanceof SysException) {
            result.setStatus(String.valueOf(((SysException) ex).getErrorCode()));
            result.setMsg(ex.getMessage());
        } else {
            result.setMsg("GlobalExceptionHandler >>> 对不起！服务器趴窝了！" + ex.getClass().getName());
        }
        String url = request.getRequestURI() + (StringUtils.isNotEmpty(request.getQueryString()) ? ("?" + request.getQueryString()) : "");
        log.error("<GlobalExceptionHandler> 发生了异常>>>>[" + url + "]" + ex.getMessage(), ex);
//        ex.printStackTrace();
        return result;
    }
}